<template>
    <div class="search-container">
        <!-- 搜索栏 -->
        <!-- Tips: 在 van-search 外层增加 form 标签，且 action 不为空，即可在 移动端键盘 中显示搜索按钮。 -->
        <form action="/">
            <van-search
                ref="vanSearch"
                v-model="searchValue" 
                show-action shape="round" 
                background="#3296fa" 
                placeholder="请输入搜索关键词" 
                @search="onSearch" 
                @cancel="onCancel" 
                @focus="isResultShow = false"
            />
        </form>

        <!-- 搜索的结果 -->
        <search-result v-if="isResultShow" :searchText="searchValue"></search-result>
        <!-- 搜索的联想建议 -->
        <search-suggestion v-else-if="searchValue" :searchText="searchValue" @searchSuggestion="onSearch"></search-suggestion>
        <!-- 搜索的历史记录 -->
        <search-history v-else :searchHistory="searchHistory" @searchHistory="onSearch" @deleteAll="searchHistory = []"></search-history>
        
    </div>
</template>

<script>
import SearchHistory from './search-history.vue';
import SearchResult from './search-result.vue';
import SearchSuggestion from './search-suggestion.vue';

import { setItem, getItem } from '@/utils/storage'

export default {
    name: 'SearchIndex',
    components: {
        SearchHistory,
        SearchResult,
        SearchSuggestion
    },
    data() {
        return {
            searchValue: '', //搜索文本
            isResultShow: false, //控制搜索结果的展示
            searchHistory: [] //搜索的历史内容
        }
    },
    watch: {
        // 监听 searchHistory 数组的变化
        searchHistory: {
            handler(newVal) {
                // 存储到本地，持久化操作
                setItem('TOUTIAO_HISTORY', newVal)
            }
        }
    },
    methods: {
        onSearch(val) {
            this.searchValue = val
            // 存储搜索历史，最新的排前面，已有重复的删去
            const index = this.searchHistory.indexOf(val)
            if(index !== -1) {
                this.searchHistory.splice(index, 1)
            }
            this.searchHistory.unshift(val)

            // 展示搜索结果
            this.isResultShow = true
        },
        onCancel() {
            this.$router.back()
        }
    },
    created() {
        // 获取本地搜索历史
        this.searchHistory = getItem('TOUTIAO_HISTORY') || []
    },
    mounted() {
        // 组件渲染完毕就让vanSearch组件里的input获取焦点
        this.$refs.vanSearch.querySelector('input').focus()
    }
}
</script>

<style lang="less" scoped>
.search-container {
    .van-search__action {
        color: white;
    }
}
</style>